package furns.web;

import furns.entity.Furn;
import furns.entity.Page;
import furns.service.FurnService;
import furns.service.impl.FurnServiceImpl;
import furns.utils.DataUtils;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@SuppressWarnings("all")
@WebServlet(name = "CustomerFurnServlet", urlPatterns = "/customerFurnServlet")
public class CustomerFurnServlet extends BasicServlet {
    //创建 furnService对象，便于调用其方法
    private FurnService furnService = new FurnServiceImpl();
    /**
     *分页请求家具信息的方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //调用service方法，获取page对象
        Page<Furn> page = furnService.page(pageNo, pageSize);
        //将page对象放入request域
        request.setAttribute("page", page);
        //请求转发到index.jsp页面，并在该页面中展示page的数据
        request.getRequestDispatcher("/views/customer/index.jsp").forward(request, response);
    }

    /**
     * 根据名字分页请求家具信息的方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void pageByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //分析：
        //1.如果存在参数name，但name未赋值，则接收到的是 ""
        //2.如果未存在参数name，则接收到的是 null 。则需要将name设置为 ""
        String name = request.getParameter("name");
        if (name == null) {
            name = "";
        }
        //调用service方法，获取page对象
        Page<Furn> page = furnService.pageByName(pageNo, pageSize,name);

        StringBuilder url = new StringBuilder("customerFurnServlet?action=pageByName");
        if (!name.equals("")) { //表示存在参数name，则将name添加到url中
            url.append("&name=").append(name);
        }
        //将该url设置为page对象的url
        page.setUrl(url.toString());
        //将page对象放入request域
        request.setAttribute("page", page);
        //请求转发到index.jsp页面，并在该页面中展示page的数据
        request.getRequestDispatcher("/views/customer/index.jsp").forward(request, response);
    }
}